//var CC_FW.utils = {};
//initialize collections

CC_FW.utils.initCollections = function(){
	//asynchronous
	//m4wd.instances.collections.controlActions = new m4wd.collections.ControlActions();
	//m4wd.instances.collections.controlActions.fetch();
};

//load assets data
CC_FW.utils.getActions = function(callBack){
	var that = this;
	$.get('assets/actions.json', function (data) {
        m4wd.defaults.controlActions = data;
        if(callBack){
        	callBack();
        }
    });	
}

CC_FW.utils.getCurrRoute = function(callBack){
	var currRoute = '';
	if(typeof Backbone.history.fragment == 'undefined'){
		var currRoute = window.location.hash.replace('#', '');
		if(currRoute.indexOf('&') != -1){
			var urlParams = currRoute.substr(currRoute.indexOf('&'));
		}
		return currRoute.replace(urlParams, '');
	}
	return Backbone.history.fragment.replace('#', '');
}

//installer script
CC_FW.utils.install = {
	run: function(){
		var installFlag = 'm4wd_install_status';
		if(window.localStorage.getItem(installFlag) != 'Y'){
			//do install here
			m4wd.dao.queryDb(m4wd.schema.car, []);
			m4wd.dao.queryDb(m4wd.schema.race, []);
			window.localStorage.setItem(installFlag, 'X');
			console.log('done install schema');
		}
		
		window.localStorage.setItem(installFlag, 'X');
		return true;
	},
	
	getSchemaQueries: function(){
		return m4wd.schema;
	}
};

//template loader
CC_FW.utils.templateLoader = {

    // Hash of preloaded templates for the app
    templates:{},

    // Recursively pre-load all the templates for the app.
    // This implementation should be changed in a production environment. All the template files should be
    // concatenated in a single file.
    load:function (names, callback) {
    	
        var that = this;
        var loadTemplate = function (index) {
            var name = names[index];
            console.log('Loading template: ' + name);
            $.get('templates/' + name + '.html?'+ new Date().getTime().toString(), function (data) {
                that.templates[name] = data;
                index++;
                if (index < names.length) {
                    loadTemplate(index);
                } else {
                    callback();
                }
            });
        };

        loadTemplate(0);
    },

    // Get template by name from hash of preloaded templates
    get:function (name) {
        return this.templates[name];
    }
    
};

CC_FW.utils.generateRandomString = function(){
	//from http://stackoverflow.com/questions/3231459/create-unique-id-with-javascript
    // always start with a letter (for DOM friendlyness)
    var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
    do {                
        // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
        var ascicode=Math.floor((Math.random()*42)+48);
        if (ascicode<58 || ascicode>64){
            // exclude all chars between : (58) and @ (64)
            idstr+=String.fromCharCode(ascicode);    
        }                
    } while (idstr.length<32);

    var timeString = CC_FW.utils.getCurrTimeStamp().toString();

   	for(var i=0;i<timeString.length;i++){
    	var lower  = 0;
    	var randomnumber = Math.floor(lower + (Math.random() * (timeString.length - lower )));
    	idstr += timeString.charAt(randomnumber);
    }

    return (idstr);
};

CC_FW.utils.getCurrTimeStamp = function(isUnix){
	if(isUnix){
		return Math.round((new Date()).getTime() / 1000);
	}else{
		return new Date().getTime();
	}
};

//determine wether a link is currently the active one
CC_FW.utils.isActiveAction = function(linkHref){
	//get the currrent route
	var currRoute = linkHref.replace('#', '');
	if(typeof Backbone.history.fragment == 'undefined'){
		if(currRoute == window.location.hash.replace('#', '')){
			return true;
		}
	}
	if(currRoute == Backbone.history.fragment){
		return true;
	}
	return false;
}

CC_FW.utils.currDate = function(asDateObj){
	var currDate = new Date();
	if((typeof asDateObj != 'undefined' || asDateObj != null) && asDateObj == true){
		return currDate;
	}else{
		return currDate.toString();
	}
	
}

CC_FW.utils.findHashParamVal = function(hashString, param){
	//from http://www.netlobo.com/url_query_string_javascript.html
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+param+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( hashString ); 
	if( results == null )    return null;  
	else    return results[1];
}

CC_FW.utils.pageIt = function(container, title){
	$(container).page();
	$(container).attr('data-title', title)
	return $(container);
};

CC_FW.utils.isDefined = function(object){
    return (typeof object != 'undefined' && object != null);
};

CC_FW.utils.isEmptyString = function(string){
    return ($.trim(string).length == 0 || /^\s*$/.test(string))? true: false;
}

/**
 * just in case you want to load the library files like jQuery etc using the framework, native add event
 */
//from
//http://www.braksator.com/how-to-make-your-own-jquery
//http://www.dustindiaz.com/rock-solid-addevent/
CC_FW.utils.addEvent = function(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
        CC_FW.utils.EventCache.add(obj, type, fn);
    } else if (obj.attachEvent) {
        obj["e" + type + fn] = fn;
        obj[type + fn] = function() {
            obj["e"+type+fn](window.event);
        };
        obj.attachEvent("on" + type, obj[type + fn]);
        CC_FW.utils.EventCache.add(obj, type, fn);
    } else {
        obj["on" + type] = obj["e" + type + fn];
    }
};
/**
 * just in case you want to load the library files like jQuery etc using the framework, native remove event
 */
//from
//http://www.braksator.com/how-to-make-your-own-jquery
//http://www.dustindiaz.com/rock-solid-addevent/
CC_FW.utils.EventCache = function() {
    var listEvents = [];
    return {
        listEvents : listEvents,
        add : function(node, sEventName, fHandler) {
            listEvents.push(arguments);
        },
        flush : function() {
            var i, item;
            for ( i = listEvents.length - 1; i >= 0; i = i - 1) {
                item = listEvents[i];
                if (item[0].removeEventListener) {
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };
                if (item[1].substring(0, 2) != "on") {
                    item[1] = "on" + item[1];
                };
                if (item[0].detachEvent) {
                    item[0].detachEvent(item[1], item[2]);
                };
                item[0][item[1]] = null;
            };
        }
    };
}();

CC_FW.utils.dateToMDY = function(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    //return '' + y +'/'+ (m<=9?'0'+m:m) +'/'+ (d<=9?'0'+d:d);
    return (m <= 9 ? '0' + m : m) + '/' + (d <= 9 ? '0' + d : d) + '/' + y;
};
